package nestings;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * 
 * 
 * Author: Seabook
 */

public class NestingsBad {
	private static final List<Character> LEFT_SYMBOLS = Arrays.asList('<', '(',
			'[', '{');
	private static final List<Character> RIGHT_SYMBOLS = Arrays.asList('>',
			')', ']', '}');

	public static void main(String[] args) {
		NestingsBad n = new NestingsBad();
		System.out.println(n.howDeep("adfsf()[]*//*[ffff]<<555>>*/"));
		// System.out.println(n.howDeep(""));

		// System.out.println(n.howDeep("<(A)(b)>"));
		// System.out.println(n.howDeep("(/*/)"));
		// System.out.println(n.howDeep("<<<</**/asdf>>>>"));
		// System.out.println(n.howDeep("abcd(A(B(C(D)C)B)A)abcd"));
		// System.out.println(n.howDeep("([)]"));
		// System.out.println(n.howDeep("([{/**/}])"));
		// System.out.println(n.howDeep("("));
		// System.out.println(n.howDeep("]["));
	}

	public int howDeep(String nested) {
		char[] nestedChars = nested.toCharArray();

		if (nestedChars != null && nestedChars.length == 0) {
			return 0;
		}

		int stackMaxDepth = 0;
		Stack<Character> charStack = new Stack<Character>();

		for (int i = 0; i < nestedChars.length; i++) {
			char currChar = nestedChars[i];
			if (LEFT_SYMBOLS.contains(currChar)) {
				charStack.push(currChar);
				stackMaxDepth = Math.max(stackMaxDepth, charStack.size());
			}

			if (RIGHT_SYMBOLS.contains(currChar)) {
				if (charStack.isEmpty()) {
					return -1;
				}

				if (!charStack.pop().equals(getMatchedLeftSymbols(currChar))) {
					return -1;
				}
			}

			if (currChar == '/') {
				int j = i + 1;
				if (j < nestedChars.length && nestedChars[j] == '*') {
					charStack.push(currChar);
					charStack.push(nestedChars[j]);
					i = j;
					stackMaxDepth = Math.max(stackMaxDepth,
							charStack.size() - 1);
				} else
					return -1;
			}

			if (currChar == '*') {
				int j = i + 1;
				if (j < nestedChars.length && nestedChars[j] == '/') {
					if (charStack.isEmpty()) {
						return -1;
					}
					if (!charStack.pop().equals(currChar)) {
						return -1;
					}
					if (!charStack.pop().equals(nestedChars[j])) {
						return -1;
					}
					i = j;
				} else
					return -1;
			}

		}

		if (charStack.isEmpty()) {
			return stackMaxDepth;
		}

		return -1;
	}

	private char getMatchedLeftSymbols(char rightSymbol) {
		if ('>' == rightSymbol) {
			return '<';
		} else if (')' == rightSymbol) {
			return '(';
		} else if (']' == rightSymbol) {
			return '[';
		} else {
			return '{';
		}
	}
}
